import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class OTPInputField extends StatefulWidget {
  final int length;
  final Function(String)? onCompleted;
  // 1. 添加一个可选的 controller 参数
  final TextEditingController? controller;

  const OTPInputField({
    super.key,
    this.length = 6,
    this.onCompleted,
    this.controller,
  });

  @override
  State<OTPInputField> createState() => _OTPInputFieldState();
}

class _OTPInputFieldState extends State<OTPInputField> {
  // 2. 将 controller 和 focusNode 声明为 late
  //    因为它们的初始化依赖于 widget
  late final TextEditingController _controller;
  late final FocusNode _focusNode;

  List<String> _digits = [];
  String _lastText = '';

  @override
  void initState() {
    super.initState();
    // 3. 决定使用哪个 controller
    //    如果外部传入了 controller，就用外部的；否则，自己创建一个。
    _controller = widget.controller ?? TextEditingController();
    _focusNode = FocusNode();

    _digits = List.filled(widget.length, '');
    _controller.addListener(_handleTextChange);
    _updateDigitsFromController(); // 初始化时也更新一次 digits

    // 自动聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        Future.delayed(const Duration(milliseconds: 500), () {
          if (!mounted) return;
          try {
            FocusScope.of(context).requestFocus(_focusNode);
          } catch (e) {
            debugPrint('聚焦失败: $e');
          }
        });
      }
    });
  }

  // 当外部 controller 的值被改变时，UI 需要同步更新
  void _updateDigitsFromController() {
    if (!mounted) return;
    final text = _controller.text;
    setState(() {
      _digits = List.generate(
        widget.length,
        (i) => i < text.length ? text[i] : '',
      );
    });
  }

  void _handleTextChange() {
    if (!mounted) return;
    String text = _controller.text;

    // 防止不必要的重复更新
    if (text == _lastText) {
      return;
    }
    _lastText = text;

    // Log.d('输入内容: $text'); // 你的日志

    // 截断过长内容 (虽然 TextField 的 maxLength 会处理，但这是一个双重保险)
    if (text.length > widget.length) {
      text = text.substring(0, widget.length);
      _controller.value = _controller.value.copyWith(
        text: text,
        selection: TextSelection.collapsed(offset: text.length),
      );
    }

    _updateDigitsFromController(); // 使用统一的方法来更新UI

    if (text.length == widget.length) {
      widget.onCompleted?.call(text);
      _focusNode.unfocus();
    }
  }

  @override
  void didUpdateWidget(covariant OTPInputField oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 4. 如果外部传入的 controller 发生了变化，需要处理
    if (widget.controller != null && widget.controller != _controller) {
      // 移除旧 controller 的监听
      _controller.removeListener(_handleTextChange);
      // 如果是自己创建的，需要 dispose
      if (oldWidget.controller == null) {
        _controller.dispose();
      }
      // 换上新的 controller
      _controller = widget.controller!;
      _controller.addListener(_handleTextChange);
      _updateDigitsFromController();
    }
  }

  @override
  void dispose() {
    _controller.removeListener(_handleTextChange);
    // 5. 只有当 controller 是内部创建的时候，才需要 dispose
    //    外部传入的 controller 由外部负责 dispose
    if (widget.controller == null) {
      _controller.dispose();
    }
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _focusNode.requestFocus(),
      child: Stack(
        children: [
          // 实际透明输入框
          Opacity(
            opacity: 0,
            child: TextField(
              controller: _controller,
              focusNode: _focusNode,
              keyboardType: TextInputType.number,
              autofillHints: const [AutofillHints.oneTimeCode],
              maxLength: widget.length,
              decoration: const InputDecoration(counterText: ''),
            ),
          ),

          // 显示格子
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: List.generate(widget.length, (index) {
              final char = _digits[index];
              final isFocused = _controller.text.length == index;
              return Container(
                width: 48.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  border: const Border(
                    bottom: BorderSide(color: Colors.grey, width: 1.0),
                  ),
                ),
                child: Text(char, style: TextStyle(fontSize: 24)),
              );
            }),
          ),
        ],
      ),
    );
  }
}
